/**
 * 管理员端 - 班级学习进度查看页面脚本
 */
$(document).ready(function() {
    // 初始化
    initPage();
    
    // 绑定事件
    bindEvents();
});

/**
 * 初始化页面
 */
function initPage() {
    // 获取URL参数中的班级ID
    const urlParams = new URLSearchParams(window.location.search);
    const classId = urlParams.get('classId');
    
    if (classId) {
        // 设置班级ID
        $('#class-id').text(classId);
        
        // 获取班级学习进度数据
        getClassLearningProgress(classId);
        
        // 获取班级科目列表并加载第一个科目
        getClassSubjects(classId);
    } else {
        showMessage('缺少班级ID参数', 'error');
    }
}

/**
 * 绑定事件
 */
function bindEvents() {
    // 返回按钮
    $('#btn-back').click(function() {
        window.history.back();
    });
    
    // 科目切换
    $('#subject-tabs').on('click', '.subject-tab', function() {
        const subject = $(this).data('subject');
        const classId = $('#class-id').text();
        
        // 激活当前标签
        $('.subject-tab').removeClass('active');
        $(this).addClass('active');
        
        // 获取该科目的详细进度数据
        getClassSubjectProgress(classId, subject);
    });
    
    // 查看学生详情
    $('#student-progress-table').on('click', '.btn-view-student', function() {
        const studentId = $(this).data('student-id');
        window.location.href = `admin-student-progress.html?studentId=${studentId}`;
    });
}

/**
 * 获取班级学习进度数据
 */
function getClassLearningProgress(classId) {
    $.ajax({
        url: `/api/admin/class/learning-progress/${classId}`,
        type: 'GET',
        headers: {
            'Authorization': localStorage.getItem('token')
        },
        success: function(data) {
            if (data.success) {
                // 显示班级基本信息
                displayClassInfo(data);
                
                // 渲染班级整体进度
                renderClassProgress(data);
                
                // 渲染学生进度表格
                renderStudentProgressTable(data.studentProgress);
                
                // 渲染学科进度图表
                renderSubjectProgressChart(data.subjectProgress);
            } else {
                showMessage(data.message, 'error');
            }
        },
        error: function(xhr) {
            console.error('获取班级学习进度失败', xhr);
            showMessage('获取班级学习进度失败: ' + getErrorMessage(xhr), 'error');
        }
    });
}

/**
 * 获取班级科目列表
 */
function getClassSubjects(classId) {
    $.ajax({
        url: `/api/admin/class/learning-progress/${classId}`,
        type: 'GET',
        headers: {
            'Authorization': localStorage.getItem('token')
        },
        success: function(data) {
            if (data.success && data.subjectProgress && data.subjectProgress.length > 0) {
                // 渲染科目标签
                renderSubjectTabs(data.subjectProgress);
                
                // 默认加载第一个科目
                const firstSubject = data.subjectProgress[0].subject;
                getClassSubjectProgress(classId, firstSubject);
                
                // 激活第一个标签
                $(`.subject-tab[data-subject="${firstSubject}"]`).addClass('active');
            }
        },
        error: function(xhr) {
            console.error('获取班级科目列表失败', xhr);
        }
    });
}

/**
 * 获取班级科目进度详情
 */
function getClassSubjectProgress(classId, subject) {
    $.ajax({
        url: `/api/admin/class/subject-progress/${classId}/${subject}`,
        type: 'GET',
        headers: {
            'Authorization': localStorage.getItem('token')
        },
        success: function(data) {
            if (data.success) {
                // 渲染该学科的学生进度表格
                renderSubjectStudentTable(data.studentProgress, subject);
                
                // 渲染知识点掌握情况
                renderKnowledgePointsChart(data.knowledgePoints, subject);
            } else {
                showMessage(data.message, 'error');
            }
        },
        error: function(xhr) {
            console.error(`获取班级${subject}学科进度失败`, xhr);
            showMessage(`获取班级${subject}学科进度失败: ` + getErrorMessage(xhr), 'error');
        }
    });
}

/**
 * 显示班级基本信息
 */
function displayClassInfo(data) {
    $('#class-name').text(data.className || data.classId || '-');
    
    // 显示练习统计数据
    if (data.practiceStats) {
        $('#total-sessions').text(data.practiceStats.total_sessions || 0);
        $('#total-questions').text(data.practiceStats.total_questions || 0);
        
        // 计算正确率
        let correctRate = 0;
        if (data.practiceStats.total_questions > 0 && data.practiceStats.correct_questions) {
            const total = parseFloat(data.practiceStats.total_questions);
            const correct = parseFloat(data.practiceStats.correct_questions);
            correctRate = Math.round((correct / total) * 100);
        }
        $('#correct-rate').text(correctRate + '%');
    }
}

/**
 * 渲染班级整体进度
 */
function renderClassProgress(data) {
    const avgProgress = data.averageProgress || 0;
    
    // 更新进度条
    $('#class-progress-bar')
        .css('width', `${avgProgress}%`)
        .attr('aria-valuenow', avgProgress)
        .text(`${avgProgress}%`);
}

/**
 * 渲染学生进度表格
 */
function renderStudentProgressTable(studentProgressData) {
    const tableBody = $('#student-progress-tbody');
    tableBody.empty();
    
    if (!studentProgressData || studentProgressData.length === 0) {
        $('#student-progress-table').hide();
        $('#no-student-data').show();
        return;
    }
    
    $('#student-progress-table').show();
    $('#no-student-data').hide();
    
    studentProgressData.forEach((student, index) => {
        const progress = parseFloat(student.avg_progress);
        const progressClass = getProgressColorClass(progress);
        
        const row = `
            <tr>
                <td>${index + 1}</td>
                <td>${student.student_id}</td>
                <td>${student.name}</td>
                <td>
                    <div class="progress">
                        <div class="progress-bar ${progressClass}" role="progressbar" 
                            style="width: ${progress}%" aria-valuenow="${progress}" 
                            aria-valuemin="0" aria-valuemax="100">
                            ${Math.round(progress)}%
                        </div>
                    </div>
                </td>
                <td>
                    <button class="btn btn-sm btn-primary btn-view-student" data-student-id="${student.student_id}">
                        查看详情
                    </button>
                </td>
            </tr>
        `;
        tableBody.append(row);
    });
}

/**
 * 渲染科目标签
 */
function renderSubjectTabs(subjectProgressData) {
    const tabsContainer = $('#subject-tabs');
    tabsContainer.empty();
    
    if (!subjectProgressData || subjectProgressData.length === 0) {
        tabsContainer.append('<div class="alert alert-info">暂无科目数据</div>');
        return;
    }
    
    subjectProgressData.forEach(subjectData => {
        const subject = subjectData.subject;
        const progress = parseFloat(subjectData.subject_progress);
        
        const tab = `
            <li class="nav-item">
                <a class="nav-link subject-tab" data-subject="${subject}" href="javascript:void(0)">
                    ${subject}
                    <span class="badge bg-primary">${Math.round(progress)}%</span>
                </a>
            </li>
        `;
        tabsContainer.append(tab);
    });
}

/**
 * 渲染学科进度图表
 */
function renderSubjectProgressChart(subjectProgressData) {
    if (!subjectProgressData || subjectProgressData.length === 0) {
        $('#subject-chart-container').hide();
        return;
    }
    
    $('#subject-chart-container').show();
    
    // 准备图表数据
    const subjects = [];
    const progressData = [];
    
    subjectProgressData.forEach(item => {
        subjects.push(item.subject);
        progressData.push(parseFloat(item.subject_progress).toFixed(1));
    });
    
    // 使用Chart.js绘制图表
    const ctx = document.getElementById('subject-progress-chart').getContext('2d');
    
    // 如果已有图表实例，销毁它
    if (window.subjectChart) {
        window.subjectChart.destroy();
    }
    
    // 创建新图表
    window.subjectChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: subjects,
            datasets: [{
                label: '科目进度',
                data: progressData,
                backgroundColor: 'rgba(54, 162, 235, 0.6)',
                borderColor: 'rgba(54, 162, 235, 1)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            scales: {
                y: {
                    beginAtZero: true,
                    max: 100,
                    title: {
                        display: true,
                        text: '完成进度(%)'
                    }
                }
            },
            plugins: {
                title: {
                    display: true,
                    text: '班级各科目学习进度'
                }
            }
        }
    });
}

/**
 * 渲染学科学生进度表格
 */
function renderSubjectStudentTable(studentData, subject) {
    const tableBody = $('#subject-student-tbody');
    tableBody.empty();
    
    if (!studentData || studentData.length === 0) {
        $('#subject-student-table').hide();
        $('#no-subject-student-data').show();
        return;
    }
    
    $('#subject-student-table').show();
    $('#no-subject-student-data').hide();
    
    // 更新表格标题
    $('#subject-student-table-title').text(`${subject}学科学生进度排名`);
    
    studentData.forEach((student, index) => {
        const progress = parseFloat(student.progress);
        const progressClass = getProgressColorClass(progress);
        
        // 计算正确率
        let accuracy = 0;
        if (student.total_questions > 0 && student.correct_questions) {
            accuracy = parseFloat(student.accuracy);
        }
        
        const row = `
            <tr>
                <td>${index + 1}</td>
                <td>${student.student_id}</td>
                <td>${student.name}</td>
                <td>${student.session_count || 0}</td>
                <td>${student.total_questions || 0}</td>
                <td>${Math.round(accuracy)}%</td>
                <td>
                    <div class="progress">
                        <div class="progress-bar ${progressClass}" role="progressbar" 
                            style="width: ${progress}%" aria-valuenow="${progress}" 
                            aria-valuemin="0" aria-valuemax="100">
                            ${Math.round(progress)}%
                        </div>
                    </div>
                </td>
                <td>
                    <button class="btn btn-sm btn-primary btn-view-student" data-student-id="${student.student_id}">
                        查看详情
                    </button>
                </td>
            </tr>
        `;
        tableBody.append(row);
    });
}

/**
 * 渲染知识点掌握情况图表
 */
function renderKnowledgePointsChart(knowledgePoints, subject) {
    const chartContainer = $('#knowledge-points-chart-container');
    
    if (!knowledgePoints || knowledgePoints.length === 0) {
        chartContainer.html('<div class="alert alert-info mt-3">暂无知识点掌握情况数据</div>');
        return;
    }
    
    // 更新标题
    $('#knowledge-points-chart-title').text(`${subject}学科知识点掌握情况`);
    
    // 准备图表数据
    const labels = [];
    const data = [];
    const backgroundColors = [];
    
    knowledgePoints.forEach(kp => {
        labels.push(kp.knowledge_point);
        const mastery = parseFloat(kp.mastery);
        data.push(mastery.toFixed(1));
        
        // 根据掌握程度设置颜色
        if (mastery >= 80) {
            backgroundColors.push('rgba(40, 167, 69, 0.6)'); // 绿色
        } else if (mastery >= 60) {
            backgroundColors.push('rgba(23, 162, 184, 0.6)'); // 蓝色
        } else if (mastery >= 40) {
            backgroundColors.push('rgba(255, 193, 7, 0.6)'); // 黄色
        } else {
            backgroundColors.push('rgba(220, 53, 69, 0.6)'); // 红色
        }
    });
    
    // 清空容器并创建新的canvas
    chartContainer.html('<canvas id="knowledge-points-chart"></canvas>');
    const ctx = document.getElementById('knowledge-points-chart').getContext('2d');
    
    // 创建图表
    new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: '掌握程度',
                data: data,
                backgroundColor: backgroundColors,
                borderColor: backgroundColors.map(color => color.replace('0.6', '1')),
                borderWidth: 1
            }]
        },
        options: {
            indexAxis: 'y',
            responsive: true,
            scales: {
                x: {
                    beginAtZero: true,
                    max: 100,
                    title: {
                        display: true,
                        text: '掌握程度(%)'
                    }
                }
            },
            plugins: {
                title: {
                    display: true,
                    text: `${subject}学科知识点掌握情况`
                }
            }
        }
    });
}

/**
 * 根据进度获取对应的颜色类
 */
function getProgressColorClass(progress) {
    if (progress >= 80) return 'bg-success';
    if (progress >= 60) return 'bg-info';
    if (progress >= 40) return 'bg-warning';
    return 'bg-danger';
}

/**
 * 显示消息
 */
function showMessage(message, type = 'success') {
    const alertClass = type === 'error' ? 'alert-danger' : 'alert-success';
    const messageHtml = `
        <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    `;
    
    $('#message-container').html(messageHtml);
    
    // 5秒后自动消失
    setTimeout(() => {
        $('.alert').alert('close');
    }, 5000);
}

/**
 * 获取错误消息
 */
function getErrorMessage(xhr) {
    if (xhr.responseJSON && xhr.responseJSON.message) {
        return xhr.responseJSON.message;
    }
    return xhr.statusText || '未知错误';
} 